package com.edu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.commonutils.R;
import com.edu.eduservice.domain.EduSubject;
import com.edu.eduservice.domain.excel.SubjectData;
import com.edu.eduservice.domain.view.SubjectType;
import com.edu.eduservice.listener.EasyExcelListener;
import com.edu.eduservice.mapper.EduSubjectMapper;
import com.edu.eduservice.service.EduSubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author ljw
 * @since 2022-09-15
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Autowired(required = false)
    private EduSubjectMapper eduSubjectMapper;

    @Override
    public void scannerexcel(MultipartFile file,EduSubjectService eduSubjectService) {

        try {
            //获取stream流
            InputStream stream = file.getInputStream();
            //读取excel
            EasyExcel.read(stream, SubjectData.class,new EasyExcelListener(eduSubjectService)).sheet().doRead();

        }catch(Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public R getSubjectService() {
        //查询到所有的分类数据
        List<EduSubject> eduSubjects = this.eduSubjectMapper.selectList(null);
        //用来存储所有的一级分类 所有的二级分类在一级分类里面
        List<SubjectType> subjectTypeList=new ArrayList<>();
        //循环所有分类数据
        for (EduSubject eduSubject : eduSubjects) {
            //拿到每一个分类
            SubjectType subjectType = new SubjectType(eduSubject.getId(), eduSubject.getTitle());
            subjectType.setChildren(new ArrayList<>());
            //判断是不是一级分类
            if(eduSubject.getParentId().equals("0")){
                //循环所有的分类 来判断是不是二级分类
                for (EduSubject twosubject : eduSubjects) {
                    //拿到所有的二级分类 根据父级编号来判断
                    if(eduSubject.getId().equals(twosubject.getParentId())){
                        SubjectType twotypesubject = new SubjectType(twosubject.getId(), twosubject.getTitle());
                        //把二级分类添加到一级分类里面
                        subjectType.getChildren().add(twotypesubject);
                    }
                }
                //把一级分类添加进入集合中返回
                subjectTypeList.add(subjectType);
            }
        }
        //封装数据并且返回
        R r = R.ok().data("list", subjectTypeList);
        return r;
    }
}
